package com.wb.common;

import com.alibaba.fastjson.JSON;
import com.haohope.framework.wb.lock.DefaultDictionaryLock;
import com.haohope.framework.wb.lock.DictionaryLock;
import com.haohope.framework.wb.online.OnlineService;
import com.haohope.framework.wb.online.OnlineSessionGridResult;
import com.haohope.framework.wb.online.OnlineSessionVo;
import com.haohope.framework.wb.online.OnlineUserGridResult;
import com.haohope.framework.wb.online.OnlineUserVo;
import com.wb.util.StringUtil;
import com.wb.util.WebUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class UserList implements ApplicationContextAware{
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private static HashMap<String, HashSet<HttpSession>> users = new HashMap();
	private static OnlineService onlineService = new DefaultOnlineServiceImpl();
	public static DictionaryLock lock = new DefaultDictionaryLock();
	public static void add(String userId, HttpSession session) {
		if (Var.recordSession) {
			doAdd(userId, session);
		}
	}
	@SuppressWarnings({ })
	private static void doAdd(String userId, HttpSession session) {
		/**
		HashSet<HttpSession> sessions = (HashSet) users.get(userId);
		if (sessions == null) {
			sessions = new HashSet();
			users.put(userId, sessions);
		}

		sessions.add(session);
		**/
		try {
    		lock.lock();
		    onlineService.doAdd(userId, session);
		}catch(Exception e) {
			throw e;
		}finally {
			lock.unlock();
		}
	}

	public static void remove(String userId, HttpSession session) {
		if (Var.recordSession) {
			doRemove(userId, session);
		}
	}
	@SuppressWarnings({ })
	private static void doRemove(String userId, HttpSession session) {
		/**
		HashSet<HttpSession> sessions = (HashSet) users.get(userId);
		if (sessions != null && session != null) {
			sessions.remove(session);
			if (sessions.isEmpty()) {
				users.remove(userId);
			}
		}
		**/
		try {
    		lock.lock();
		    onlineService.doRemove(userId, session);
		}catch(Exception e) {
			throw e;
		}finally {
			lock.unlock();
		}
	}

	public static void invalidate(String[] userIds) {
		if (Var.recordSession) {
			doInvalidate(userIds);
		}

	}

	@SuppressWarnings({ })
	private static void doInvalidate(String[] userIds) {
		/**
		String[] var6 = userIds;
		int var5 = userIds.length;

		for (int var4 = 0; var4 < var5; ++var4) {
			String userId = var6[var4];
			HashSet<HttpSession> sessions = (HashSet) users.get(userId);
			if (sessions != null) {
				HttpSession[] sessionArray = (HttpSession[]) sessions.toArray(new HttpSession[sessions.size()]);
				HttpSession[] var10 = sessionArray;
				int var9 = sessionArray.length;

				for (int var8 = 0; var8 < var9; ++var8) {
					HttpSession session = var10[var8];

					try {
						session.invalidate();
					} catch (Throwable var12) {
						;
					}
				}

				users.remove(userId);
			}
		}
		**/
		try {
    		lock.lock();
		    onlineService.doInvalidate(userIds);
		}catch(Exception e) {
			throw e;
		}finally {
			lock.unlock();
		}
	}

	public static void update(String userId, String[] roles, boolean status) {
		if (Var.recordSession) {
			doUpdate(userId, roles, status);
		}

	}

	@SuppressWarnings({ })
	private static void doUpdate(String userId, String[] roles, boolean status) {
		/**
		HashSet<HttpSession> sessions = (HashSet) users.get(userId);
		if (sessions != null) {
			if (status) {
				Iterator var5 = sessions.iterator();

				while (var5.hasNext()) {
					HttpSession session = (HttpSession) var5.next();

					try {
						session.setAttribute("sys.roles", roles);
						session.setAttribute("sys.roleList", StringUtil.join(roles, ","));
					} catch (Throwable var7) {
						;
					}
				}
			} else {
				String[] userIds = new String[]{userId};
				invalidate(userIds);
			}
		}
		**/
		try {
    		lock.lock();
		    onlineService.doUpdate(userId, roles, status);
		}catch(Exception e) {
			throw e;
		}finally {
			lock.unlock();
		}

	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static HttpSession[] getSessions(String userId) {
		try {
    		lock.lock();
		    HashSet<HttpSession> sessions = (HashSet) users.get(userId);
		    return sessions == null ? null : (HttpSession[]) sessions.toArray(new HttpSession[sessions.size()]);
		}catch(Exception e) {
			throw e;
		}finally {
			lock.unlock();
		}
	}
	public static String[] getUsers() {
		try {
    		lock.lock();
		    return (String[]) users.keySet().toArray(new String[users.size()]);
		}catch(Exception e) {
			throw e;
		}finally {
			lock.unlock();
		}
	}

	public static void getSessionList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (Var.recordSession) {
			doGetSessionList(request, response);
		}

	}
	private static void doGetSessionList(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String user = request.getParameter("user");
		int start = Integer.parseInt(request.getParameter("start"));
		int limit = Integer.parseInt(request.getParameter("limit"));
		/*
		int index = -1;
		JSONArray rows = new JSONArray();
		HashSet<HttpSession> sessions = (HashSet) users.get(user);
		if (limit > Var.limitRecords) {
			limit = Var.limitRecords;
		}

		int end = start + limit;
		if (sessions != null) {
			Iterator var12 = sessions.iterator();

			while (var12.hasNext()) {
				HttpSession session = (HttpSession) var12.next();
				++index;
				if (index >= start) {
					if (index >= end) {
						break;
					}

					JSONObject row = new JSONObject();

					try {
						row.put("ip", session.getAttribute("sys.ip"));
						row.put("userAgent", session.getAttribute("sysx.userAgent"));
						row.put("createDate", new Date(session.getCreationTime()));
						row.put("lastAccessDate", new Date(session.getLastAccessedTime()));
						rows.put(row);
					} catch (Throwable var14) {
						--index;
					}
				}
			}
		}

		JSONObject result = new JSONObject();
		result.put("rows", rows);
		result.put("total", sessions == null ? 0 : sessions.size());
		WebUtil.send(response, result);
		*/
		WebUtil.send(response, onlineService.doGetSessionList(user, start, limit));
	}

	public static void getUserList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (Var.recordSession) {
			doGetUserList(request, response);
		}

	}
	private static void doGetUserList(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		int start = Integer.parseInt(request.getParameter("start"));
		int limit = Integer.parseInt(request.getParameter("limit"));
		/*
		int index = -1;
		JSONArray rows = new JSONArray();
		Set<Entry<String, HashSet<HttpSession>>> es = users.entrySet();
		if (limit > Var.limitRecords) {
			limit = Var.limitRecords;
		}

		int end = start + limit;
		Iterator var14 = es.iterator();

		while (var14.hasNext()) {
			Entry<String, HashSet<HttpSession>> e = (Entry) var14.next();
			++index;
			if (index >= start) {
				if (index >= end) {
					break;
				}

				HashSet<HttpSession> sessions = (HashSet) e.getValue();
				int sessionCount = 0;
				HttpSession session = null;

				for (Iterator var16 = sessions.iterator(); var16.hasNext(); ++sessionCount) {
					HttpSession sess = (HttpSession) var16.next();
					if (session == null) {
						session = sess;
					}
				}

				if (sessionCount != 0) {
					JSONObject row = new JSONObject();
					row.put("sessionCount", sessionCount);
					row.put("user", e.getKey());

					try {
						row.put("username", session.getAttribute("sys.username"));
						row.put("dispname", session.getAttribute("sys.dispname"));
						row.put("ip", session.getAttribute("sys.ip"));
						row.put("userAgent", session.getAttribute("sysx.userAgent"));
						rows.put(row);
					} catch (Throwable var17) {
						--index;
					}
				}
			}
		}

		JSONObject result = new JSONObject();
		result.put("rows", rows);
		result.put("total", users.size());
		onlineService.doGetUserList(start, limit);
		 */
		WebUtil.send(response, JSON.toJSONString(onlineService.doGetUserList(start, limit)));
	}
	
	static class DefaultOnlineServiceImpl implements OnlineService{

		@SuppressWarnings({ "rawtypes", "unchecked" })
		@Override
		public OnlineUserGridResult doGetUserList(int start, int limit) {
			int index = -1;
			List<OnlineUserVo> rows = new ArrayList<OnlineUserVo>();
			Set<Entry<String, HashSet<HttpSession>>> es = users.entrySet();
			if (limit > Var.limitRecords) {
				limit = Var.limitRecords;
			}

			int end = start + limit;
			Iterator var14 = es.iterator();

			while (var14.hasNext()) {
				Entry<String, HashSet<HttpSession>> e = (Entry) var14.next();
				++index;
				if (index >= start) {
					if (index >= end) {
						break;
					}

					HashSet<HttpSession> sessions = (HashSet) e.getValue();
					int sessionCount = 0;
					HttpSession session = null;

					for (Iterator var16 = sessions.iterator(); var16.hasNext(); ++sessionCount) {
						HttpSession sess = (HttpSession) var16.next();
						if (session == null) {
							session = sess;
						}
					}

					if (sessionCount != 0) {
						OnlineUserVo row = new OnlineUserVo();
						row.setSessionCount(sessionCount);
						row.setUser(e.getKey());

						try {
							row.setUsername((String)session.getAttribute(OnlineService.USERNAME));
							row.setDispname((String)session.getAttribute(OnlineService.DISPNAME));
							row.setIp((String)session.getAttribute(OnlineService.IP));
							row.setUserAgent((String)session.getAttribute(OnlineService.USERAGENT));
							rows.add(row);
						} catch (Throwable var17) {
							--index;
						}
					}
				}
			}
			return new OnlineUserGridResult(users.size(),rows);
		}

		@SuppressWarnings({ "rawtypes", "unchecked" })
		@Override
		public OnlineSessionGridResult doGetSessionList(String user,int start, int limit) {
			int index = -1;
			List<OnlineSessionVo> rows = new ArrayList<OnlineSessionVo>();
			HashSet<HttpSession> sessions = (HashSet) users.get(user);
			if (limit > Var.limitRecords) {
				limit = Var.limitRecords;
			}

			int end = start + limit;
			if (sessions != null) {
				Iterator var12 = sessions.iterator();

				while (var12.hasNext()) {
					HttpSession session = (HttpSession) var12.next();
					++index;
					if (index >= start) {
						if (index >= end) {
							break;
						}

						OnlineSessionVo row = new OnlineSessionVo();

						try {
							row.setIp((String)session.getAttribute(OnlineService.IP));
							row.setUserAgent((String)session.getAttribute(OnlineService.USERAGENT));
							row.setCreateDate(new Date(session.getCreationTime()));
							row.setLastAccessDate(new Date(session.getLastAccessedTime()));
							rows.add(row);
						} catch (Throwable var14) {
							--index;
						}
					}
				}
			}
			return new OnlineSessionGridResult(sessions == null ? 0l : sessions.size(),rows);
		}

		@SuppressWarnings({ "rawtypes", "unchecked" })
		@Override
		public void doAdd(String userId, HttpSession session) {
			HashSet<HttpSession> sessions = (HashSet) users.get(userId);
			if (sessions == null) {
				sessions = new HashSet();
				users.put(userId, sessions);
			}else {
				/*
				boolean uniqueLogin = Var.getBool("sys.session.uniqueLogin");
				if(uniqueLogin && sessions.size() > 0) {
					for(HttpSession _session:sessions) {
						_session.invalidate();
					}
					sessions.clear();
				}*/
			}
			sessions.add(session);
		}

		@SuppressWarnings({ "unchecked", "rawtypes" })
		@Override
		public void doRemove(String userId, HttpSession session) {
			HashSet<HttpSession> sessions = (HashSet) users.get(userId);
			if (sessions != null && session != null) {
				sessions.remove(session);
				if (sessions.isEmpty()) {
					users.remove(userId);
				}
			}
			
		}

		@SuppressWarnings({ "unchecked", "rawtypes" })
		@Override
		public void doInvalidate(String[] userIds) {
			String[] var6 = userIds;
			int var5 = userIds.length;

			for (int var4 = 0; var4 < var5; ++var4) {
				String userId = var6[var4];
				HashSet<HttpSession> sessions = (HashSet) users.get(userId);
				if (sessions != null) {
					HttpSession[] sessionArray = (HttpSession[]) sessions.toArray(new HttpSession[sessions.size()]);
					HttpSession[] var10 = sessionArray;
					int var9 = sessionArray.length;

					for (int var8 = 0; var8 < var9; ++var8) {
						HttpSession session = var10[var8];

						try {
							session.invalidate();
						} catch (Throwable var12) {
							;
						}
					}

					users.remove(userId);
				}
			}
			
		}

		@SuppressWarnings({ "rawtypes", "unchecked" })
		@Override
		public void doUpdate(String userId, String[] roles, boolean status) {
			HashSet<HttpSession> sessions = (HashSet) users.get(userId);
			if (sessions != null) {
				if (status) {
					Iterator var5 = sessions.iterator();

					while (var5.hasNext()) {
						HttpSession session = (HttpSession) var5.next();

						try {
							session.setAttribute("sys.roles", roles);
							session.setAttribute("sys.roleList", StringUtil.join(roles, ","));
						} catch (Throwable var7) {
							;
						}
					}
				} else {
					String[] userIds = new String[]{userId};
					invalidate(userIds);
				}
			}
			
		}	
	}
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		Map<String,OnlineService> onlineServicemap = applicationContext.getBeansOfType(OnlineService.class);
		if(null!=onlineServicemap) {
			for(Entry<String, OnlineService> entry:onlineServicemap.entrySet()) {
				onlineService = entry.getValue();
				break;
			}
		}
		Map<String,DictionaryLock> lockmap = applicationContext.getBeansOfType(DictionaryLock.class);
		if(null!=lockmap) {
			for(Entry<String, DictionaryLock> entry:lockmap.entrySet()) {
				lock = entry.getValue();
				break;
			}
		}
	}
}